*******************************************************************************
* > Loop over subgroups
*******************************************************************************

foreach subgroup in All Democrat Republican {

*******************************************************************************
* >> Loop over datasets
*******************************************************************************

foreach dataset in gallup gss {

*******************************************************************************
* Load data
*******************************************************************************

use dataset_`dataset', clear
	
*******************************************************************************
* Keep the subgroup
*******************************************************************************

keep if subgroup == "`subgroup'"

*******************************************************************************
* Set params based on data set
*******************************************************************************

if "`dataset'" == "gallup" {
	rename conf Y
	local mytitle2 "Confidence (Gallup)"
	local treated_target "police"
	local yaxis -.3(.2).5
	local xaxis 1990(8)2022
}
if "`dataset'" == "gss" {
	rename nat Y
	local mytitle2 "Spending (GSS)"
	local treated_target "crimy"
	local yaxis -.6(.2).6
	local xaxis 1982(8)2022	
}

*******************************************************************************
* Label lines if it's the first plot
*******************************************************************************

local legend1 legend(off)
local legend2 legend(off)
if "`subgroup'" == "All" & "`dataset'" == "gallup" {
	local legend1 legend(order(1 ///
		"{fontface monospace:{bf:SCM}}" ///
		2 "{fontface monospace:{bf:SCM (leave-one-out)}}") ///
		symysize(0) symxsize(0) ring(0) pos(11) cols(1) ///
		region(lwid(none)))
	
}

*******************************************************************************
* Make lags
*******************************************************************************

su year
local mymin = r(min)

local lags
levelsof year if year < 2014, local(levels)
foreach i of local levels {
	egen Y`i'm = mean(Y) if year == `i', by(target)
	egen Y`i' = mean(Y`i'm), by(target)
	drop Y`i'm
	local lags `lags' Y`i'
}

*******************************************************************************
* Do synth without leaving any out
*******************************************************************************

encode target, gen(id)
tsset id year
local i = 1

su id if target == "`treated_target'"
local treated = r(mean)
synth Y `lags', trunit(`treated') trperiod(2014) keep(tmp0, replace)
save tmp, replace

*******************************************************************************
* Get the units with positive weight
*******************************************************************************

use tmp0, clear
keep if _W_ > 0
decode _Co_Number, gen(target)
keep target
keep if !mi(target)
gen posweight = 1

*******************************************************************************
* Merge back to original data set
*******************************************************************************

merge 1:m target using tmp
erase tmp.dta
drop _m

*******************************************************************************
* >>> Loop over targets with positive weight
*******************************************************************************

levelsof target if posweight == 1, local(levels)
local nlevels = r(r)
foreach l of local levels {
	
	preserve
	
	drop if target == "`l'"
	
*******************************************************************************
* Do the synth
*******************************************************************************

	#delimit;

	synth 
		Y `lags',
			trunit(`treated')
			trperiod(2014)   
			keep(tmp_`i', replace)
			;

	#delimit cr
	
	restore
		
	preserve
		use tmp_`i', clear
		gen target = "`l'"
		save tmp_`i', replace
	restore

	local i = `i' + 1

*******************************************************************************
* >>> Close loop over targets with positive weight
*******************************************************************************
	
}

*******************************************************************************
* Graph all leave-one-out series
*******************************************************************************

use tmp0, clear
gen target = "`treated_target'"
erase tmp0.dta
forvalues i = 1(1)`nlevels' {
	append using tmp_`i'
	erase tmp_`i'.dta
}

gen D = _Y_treat - _Y_syn
sort target _time
encode target, gen(targetid)

levelsof targetid, local(levels)
foreach l of local levels {
	local p (line D _time if targetid == `l', col(gray))
	local placebos `placebos' `p'
}

#delimit;

gr tw
	`placebos'
	(line D _time if target == "`treated_target'", col(black))
	,
		`legend1'
		xline(2014, lpat(dash))
		yline(0, lpat(shortdash))
		name(g`dataset', replace)
		plotregion(style(none))
		ylab(`yaxis', angle(horiz))
		ytitle("")
		xtitle("")
		xlab(`xaxis')
		title(`mytitle2')
		;

#delimit cr

gr_edit .legend.plotregion1.label[2].style.editstyle color(gray) editcopy

*******************************************************************************
* >> Close data setloop
*******************************************************************************

}

*******************************************************************************
* Combine plots for each dataset
*******************************************************************************

local mytitle `subgroup'
if "`subgroup'" != "All" local mytitle = "`subgroup's" 

gr combine ggallup ggss, name(G`subgroup', replace) title(`mytitle')

*******************************************************************************
* > Close subgroup loop
*******************************************************************************

}

*******************************************************************************
* Combine plots for each subgroup
*******************************************************************************

gr combine GAll GDemocrat GRepublican, rows(3) ysize(4) xsize(3) ///
	imargin(zero)
	
*******************************************************************************
* Save
*******************************************************************************

gr export "figure_leave_one_out.pdf", replace

*******************************************************************************
* End
*******************************************************************************
